<?php

class NewsAction extends CommonAction {

    public function index() {
//            die(".............");
        $M = M("News");
//        die(".............");
        $count = $M->count();
        import("ORG.Util.Page");       //载入分页类
        $page = new Page($count, 20);
        $showPage = $page->show();
        $this->assign("page", $showPage);
        $this->assign("list", D("News")->listNews($page->firstRow, $page->listRows));
        $this->display();
    }

    public function category() {
        if (IS_POST) {
            echo json_encode(D("News")->category());
        } else {
            $this->assign("list", D("News")->category());
            $this->display();
        }
    }

    public function add() {
        if (IS_POST) {
            $this->checkToken();
            echo json_encode(D("News")->addNews());
        } else {
            $this->assign("list", D("News")->category());
            $this->display();
        }
    }

    public function checkCategory($name){
        $category = M('Category');

        $where = "name='" . $name . "'";

        $result = $category->where($where)->select();

        if ($result) {
            $cid = $result['cid'];
        } else {
            $data['pid'] = 0;
            $data['name'] = $name;
            $cid = $category->add($data);
        }

        return $cid ? $cid :1;
    }

    public function checkTag($name,$category){
        $tag = M('Tag');

        $where = "name='" . $name . "'";
        $where.=" And cid =" . $category;

        $result = $tag->where($where)->select();

        if ($result['id']) {
            $id = $result['id'];
        } else {
            $data['cid'] = $category;
            $data['name'] = $name;
            $id = $tag->add($data);
        }

        return $id ? $id :1;
    }

    public function checkTagNew($tag_id,$new_id){
        $tag_new = M('TagNew');

        $where = "tag_id='" . $tag_id . "'";
        $where.=" And new_id =" . $new_id;

        $result = $tag_new->where($where)->select();

        if (!$result) {
            $data['tag_id'] = $tag_id;
            $data['new_id'] = $new_id;
            $result = $tag_new->add($data);
        }

        return $result;
    }

    public function addNew(){
        set_time_limit(0);
        $news = M('News');


        $info = array();
        $p_id = $_GET['id'];
        $type = $_GET['type'];

        $info['title'] = $_GET['title'];

        $check_news_title = $news->where($info)->field('id')->find();

        if($check_news_title != null){
            echo json_encode(array("status" => 2, "id" => $check_news_title));
            exit;
        }

        import('ORG.Spider.simple_html_dom');

        $info['published'] = strtotime($_GET['time']);

        $info['cid'] = $this->checkCategory($type);

        //信息抓取
        $html = file_get_html('http://www.36kr.com/p/'.$p_id);

        $keywords_dom = $html->find('meta[name=keywords]', 0);
        $info['keywords'] =  $keywords_dom->content;

        $description_dom = $html->find('meta[name=description]', 0);
        $info['description'] =  $description_dom->content;

        if(!empty($_GET['summary'])){
            $info['summary'] =  $_GET['summary'];
        }else{
            $info['summary'] =  $info['description'];
        }

        $content = '';
        foreach ($html->find('div.mainContent p') as $element){
            $content .= $element->outertext;
        }
        $info['content'] = rep_img_src($content,$_GET['time']);

        $preImg = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.bmp|\.jpeg]))[\'|\"].*?[\/]?>/";
        preg_match_all($preImg, $info['content'], $arr); //$content为原始文章内容，下同

        $dir = 'Uploads/image/'.date('Ymd',strtotime($_GET['time'])).'/';
        if (!file_exists($dir.'thumb/')) {
            mkdir($dir.'thumb/',0777,true);
        }
        $picName = pathinfo($arr[1][0]);    //获取图片名
        $picName['basename'] = explode('!',$picName['basename']);
        $picName['basename'] = $picName['basename'][0];
        $file_name = date('YmdHis',strtotime($_GET['time'])) . '_' . rand(1,999999999) . '.' . $picName['extension'];
        $file_name = explode('!',$file_name);
        $file_name = $file_name[0];

        $retsult_status = imagezoom( $dir.$picName['basename'], $dir.'thumb/'.$file_name, 320, 200, '#FFFFFF');

        if($retsult_status != 1){
            $this->error("抓取新闻生成图片失败，请联系管理员检查！#".$retsult_status);
        }
        $info['picture'] = $dir.'thumb/'.$file_name;

        $tag = '';
        $tag_id_arr = array();
        foreach ($html->find('a.tag') as $element){
            $tag .= !empty($tag) ? ',' . $element->plaintext : $element->plaintext;

            $tag_id_arr[] = $this->checkTag($element->plaintext,$info['cid']);
        }

        $info['tag'] = $tag;

        $info['aid'] = $_SESSION['my_info']['aid'];

        //去除 36氪站 新闻
        if(strpos($info['title'],'36kr') || strpos($info['title'],'氪') || strpos($info['content'],'36kr') || strpos($info['content'],'氪')){
            $info['status'] = 0;
            //echo json_encode(array("status" => 1, "id" => "is 36kr new~"));
            //exit;
        }else{
            $info['status'] = 1;
        }

        $result = $news->add($info);

        if($result){
            foreach($tag_id_arr as $v){
                $this->checkTagNew($v,$result);
            }
        }

        echo json_encode(array("status" => 1, "id" => $result));

        $html->clear();

        exit;
    }

    public function spiderBatch(){
        set_time_limit(0);
        $type = @$_GET['type'];
        $page = @$_GET['page'];
        if(isset($type) && $type != null){
            import('ORG.Spider.simple_html_dom');
            $html = file_get_html('http://www.36kr.com/category/'.$type.'?page='.$page);

            $arr = array();

            $new_info_dom = $html->find('div.'.$type);

            foreach($new_info_dom as $k=>$v){

                $info = array();

                $info['href'] = 'http://www.36kr.com'.$v->find('div.left_info div.feature_img a',0)->href;
                $info['src'] = $v->find('div.left_info div.feature_img a img',0)->src;

                $info['title'] = $v->find('div.right_info div.summary h4 a',0)->plaintext;

                $info['type'] = $v->find('div.right_info div.post_meta a',1)->plaintext;
                $info['time'] = date('Y-m-d H:i:s', strtotime($v->find('div.right_info div.post_meta abbr',0)->title));
                $info['summary'] = $v->find('div.right_info div.excerpt p',0)->plaintext;

                $arr[$k] = $info;

            }

            echo json_encode(array("status" => 1, "info" => array_reverse($arr)));
            $html->clear();

            exit;
        }
        $this->assign('type','Batch');
        $this->display('spider');
    }

    public function spiderSingle(){
        set_time_limit(0);
        $p_id = @$_GET['p_id'];
        if (IS_POST) {
            $this->checkToken();
            import('ORG.Spider.simple_html_dom');
            $_POST['info']['content'] = rep_img_src($_POST['info']['content']);

            $preImg = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.bmp|\.jpeg]))[\'|\"].*?[\/]?>/";
            preg_match_all($preImg, $_POST['info']['content'], $arr); //$content为原始文章内容，下同

            $dir = 'Uploads/image/'.date('Ymd').'/';
            if (!file_exists($dir.'thumb/')) {
                mkdir($dir.'thumb/',0777,true);
            }
            $picName = pathinfo($arr[1][(int)$_POST['info']['picture']-1]);    //获取图片名
            $picName['basename'] = explode('!',$picName['basename']);
            $picName['basename'] = $picName['basename'][0];
            $file_name = date('YmdHis') . '_' . rand(1,999999999) . '.' . $picName['extension'];
            $file_name = explode('!',$file_name);
            $file_name = $file_name[0];

            $retsult_status = imagezoom( $dir.$picName['basename'], $dir.'thumb/'.$file_name, 320, 200, '#FFFFFF');

            if($retsult_status != 1){
                $this->error("抓取新闻生成图片失败，请联系管理员检查！@".$retsult_status);
            }
            $_POST['info']['picture'] = $dir.'thumb/'.$file_name;
            echo json_encode(D("News")->addNews());
            exit;
        }elseif($p_id){
            import('ORG.Spider.simple_html_dom');

            $html = file_get_html('http://www.36kr.com/p/'.$p_id);

            $info = array();
            $keywords_dom = $html->find('meta[name=keywords]', 0);
            $info['keywords'] =  $keywords_dom->content;

            $description_dom = $html->find('meta[name=description]', 0);
            $info['description'] =  $description_dom->content;
            $info['summary'] =  $description_dom->content;

            $title_dom = $html->find('h1.entry-title', 0);
            $info['title'] = $title_dom->plaintext;

            $content = '';
            foreach ($html->find('div.mainContent p') as $element){
                $content .= $element->outertext;
            }
            $info['content'] = $content;

            $preImg = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.bmp|\.jpeg]))[\'|\"].*?[\/]?>/";
            preg_match_all($preImg, $content, $arr); //$content为原始文章内容，下同
            $info['picture'] = count($arr[1]);

            $tag = '';
            foreach ($html->find('a.tag') as $element){
                $tag .= !empty($tag) ? ',' . $element->plaintext : $element->plaintext;
            }

            $info['tag'] = $tag;

            echo json_encode(array("status" => 1, "info" => $info));
            $html->clear();

            exit;
        }
        $this->assign("list", D("News")->category());
        $this->assign('type','Single');
        $this->display('spider');
    }

    public function checkNewsTitle() {
        $M = M("News");
        $where = "title='" . $this->_get('title') . "'";
        if (!empty($_GET['id'])) {
            $where.=" And id !=" . (int) $_GET['id'];
        }
        if ($M->where($where)->count() > 0) {
            echo json_encode(array("status" => 0, "info" => "已经存在，请修改标题"));
        } else {
            echo json_encode(array("status" => 1, "info" => "可以使用"));
        }
    }

    public function edit() {
        $M = M("News");
        if (IS_POST) {
            $this->checkToken();
            echo json_encode(D("News")->edit());
        } else {
            $info = $M->where("id=" . (int) $_GET['id'])->find();
            if ($info['id'] == '') {
                $this->error("不存在该记录");
            }
            $this->assign("info", $info);
            $this->assign("list", D("News")->category());
            $this->display("add");
        }
    }

    public function del() {
        if (M("News")->where("id=" . (int) $_GET['id'])->delete()) {
            $this->success("成功删除");
//            echo json_encode(array("status"=>1,"info"=>""));
        } else {
            $this->error("删除失败，可能是不存在该ID的记录");
        }
    }

    public function tag() {
//            die(".............");
        $M = M("Tag");
//        die(".............");
        $count = $M->count();
        import("ORG.Util.Page");       //载入分页类
        $page = new Page($count, 20);
        $showPage = $page->show();
        $this->assign("page", $showPage);
        $this->assign("list", D("Tag")->listTag($page->firstRow, $page->listRows));
        $this->display('tag');
    }

    public function tagAdd() {
        if (IS_POST) {
            $this->checkToken();
            echo json_encode(D("Tag")->addTag());
        } else {
            $this->assign("list", D("News")->category());
            $this->display('tag_add');
        }
    }

    public function checkTagName() {
        $M = M("Tag");
        $where = "name='" . $this->_get('name') . "'";
        if (!empty($_GET['id'])) {
            $where.=" And id !=" . (int) $_GET['id'];
        }
        if ($M->where($where)->count() > 0) {
            echo json_encode(array("status" => 0, "info" => "已经存在，请修改名称"));
        } else {
            echo json_encode(array("status" => 1, "info" => "可以使用"));
        }
    }

    public function tagEdit() {
        $M = M("Tag");
        if (IS_POST) {
            $this->checkToken();
            echo json_encode(D("Tag")->edit());
        } else {
            $info = $M->where("id=" . (int) $_GET['id'])->find();
            if ($info['id'] == '') {
                $this->error("不存在该记录");
            }
            $this->assign("info", $info);
            $this->assign("list", D("News")->category());
            $this->display("tag_add");
        }
    }

    public function tagDel() {
        if (M("Tag")->where("id=" . (int) $_GET['id'])->delete()) {
            $this->success("成功删除");
//            echo json_encode(array("status"=>1,"info"=>""));
        } else {
            $this->error("删除失败，可能是不存在该ID的记录");
        }
    }
}